#include "ThreadPool.h"

using namespace std;


class MyTask :public Task {
public:
    MyTask(uLong begin, uLong end)
        :begin_(begin), end_(end) {
    }

    Any run() {
        /*std::cout << "tid: " << std::this_thread::get_id()
            << " begin!" << std::endl;*/
        printf("Thread:%d  Start Sleep for 1s\n", std::this_thread::get_id());
        std::this_thread::sleep_for(std::chrono::seconds(1));
        uLong sum = 0;
        for (int i = 0;i < end_ - begin_;i++)
            sum += i;
        /*std::cout << "tid: " << std::this_thread::get_id()
            << " end!" << std::endl; */
        return sum;
    }
private:
    uLong begin_;
    uLong end_;
};

class MyTask1 :public Task {
public:
    MyTask1() = default;
    Any run() override {
        this_thread::sleep_for(std::chrono::seconds(3));
        cout << "This thread will return a bool TRUE" << endl;
        return true;
    }
};

int main()
{
    {
        ThreadPool pool;
        pool.setMode(PoolMode::MODE_CACHED);
        pool.start(4);
        Result res1 = pool.submitTask(std::make_shared<MyTask>(1, 100000));
        Result res2 = pool.submitTask(std::make_shared<MyTask>(100001, 200000));
        Result res3 = pool.submitTask(std::make_shared<MyTask>(200001, 300000));
        Result res4 = pool.submitTask(std::make_shared<MyTask>(300001, 400000));
        Result res5 = pool.submitTask(std::make_shared<MyTask>(400001, 500000));
        Result res6 = pool.submitTask(std::make_shared<MyTask>(500001, 600000));
        Result res7 = pool.submitTask(std::make_shared<MyTask1>());
        uLong sum1 = res1.get().cast_<uLong>();
        uLong sum2 = res2.get().cast_<uLong>();
        uLong sum3 = res3.get().cast_<uLong>();
        uLong sum4 = res4.get().cast_<uLong>();
        uLong sum5 = res5.get().cast_<uLong>();
        uLong sum6 = res6.get().cast_<uLong>();
        bool flag = false;
        flag = res7.get().cast_<bool>();
        std::cout << "结果为：" << (sum1 + sum2 + sum3 + sum4 + sum5 + sum6) << std::endl;
        if (flag) {
            cout << "RETURN TRUE!!!" << endl;
        }
        //Master - Slvae线程模型
        //Master线程分解任务，然后给各个Slave线程分配任务
        //等待各个Slave线程执行完成，返回结果
        //Master线程合并各个任务结果
        getchar();
        printf("main over!!!\n");
    }
    return 0;
}
